import { GameListRep, searchGameListApi } from "@/api/home";
import Card from "@/components/Card/Card";
import Empty from "@/components/Empty";
import { GameListTypeEnum } from "@/enums";
import { debounce } from "@/utils/methods";
import { InfiniteScroll } from "antd-mobile";
import React from "react";
import styles from "./page.module.scss";

interface Props {
    actInfo?: { type: GameListTypeEnum; id: number } | null;
}

const Left: React.FC<Props> = ({ actInfo }) => {
    const [data, setData] = React.useState<GameListRep[]>([]);
    const [loading, setLoading] = React.useState<boolean>(false);
    const [hasMore, setHasMore] = React.useState(true);
    const [isInit, setIsInit] = React.useState(true);
    const PageRef = React.useRef({
        current_page: 0,
        page_size: 15,
    });

    React.useEffect(() => {
        setData([]);
        setHasMore(true);
        setLoading(false);
        setIsInit(true);
        PageRef.current.current_page = 0;
    }, [actInfo]);

    const getData = async () => {
        if (!actInfo?.id) return;
        try {
            setLoading(true);
            setIsInit(false);
            const params: any = {
                ...PageRef.current,
                use_page: true,
            };

            if (actInfo) {
                params[actInfo.type] = actInfo.id;
            }

            const res = await searchGameListApi(params);
            if (res.data) {
                const toData = [...data, ...res.data];
                setData(toData);
                if (toData.length >= res.page.total_count) {
                    setHasMore(false);
                }
            }
        } finally {
            setLoading(false);
        }
    };
    const loadMore = debounce(async () => {
        if (!hasMore || loading || !actInfo?.id) return;
        PageRef.current.current_page += 1;
        getData();
    }, 500) as () => Promise<void>;

    return (
        <div className={styles.right}>
            <div className={styles.rightBox}>
                {data.map((item) => {
                    return (
                        <Card
                            key={item.id}
                            item={item}
                            className={styles.gameCard}
                            isShowFavorite={true}
                            isShowOnline={true}
                        ></Card>
                    );
                })}
            </div>
            {(isInit || data.length > 0) && (
                <InfiniteScroll loadMore={loadMore} hasMore={hasMore}></InfiniteScroll>
            )}

            {!isInit && !loading && data.length <= 0 && <Empty></Empty>}
        </div>
    );
};
export default React.memo(Left);
